package a07_二叉树;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * a02_二叉树的递归遍历复习3
 * </p>
 *
 * @author flyduck
 * @since 2025/4/2
 */
public class a02_二叉树的递归遍历复习3 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1,
                null,
                new TreeNode(2,
                        new TreeNode(3),
                        null));
        a02_二叉树的递归遍历复习3 test = new a02_二叉树的递归遍历复习3();
        System.out.println(test.preorderTraversal(root));
    }

    //前序遍历：中左右
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        preorderTraversal(root, result);
        return result;
    }

    private void preorderTraversal(TreeNode node,List<Integer> result){
        if (node == null) {
            return;
        }
        result.add(node.val);
        preorderTraversal(node.left,result);
        preorderTraversal(node.right,result);
    }

    //中序遍历：左中右
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        inorderTraversal(root, result);
        return result;
    }

    public void inorderTraversal(TreeNode node,List<Integer> result) {
        if (node == null) {
            return;
        }

        inorderTraversal(node.left, result);
        result.add(node.val);
        inorderTraversal(node.right, result);
    }

    //后序遍历：左右中
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        postorderTraversal(root, result);
        return result;
    }

    public void postorderTraversal(TreeNode node,List<Integer> result) {
        if (node == null) {
            return;
        }

        postorderTraversal(node.left, result);
        postorderTraversal(node.right, result);
        result.add(node.val);
    }
}
